package com.group7.mall.util;


import com.group7.mall.bean.JsonResult;
import com.jcraft.jsch.*;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 已弃用
 */
@Component
public class UploadFileToRemoteUtils {

    public static JsonResult uploadFileToRemoteServer(MultipartFile file, String remoteDir) {
        String remoteHost = "117.72.40.8";
        int remotePort = 22; // 注意：SSH通常使用22端口，这里假设你使用的是非标准端口
        String remoteUser = "zuoshenge";
        String remotePassword = "2002916Cjr,";
//        String remoteDir = "/opt/docker/apache/www/images"; // 远程服务器上的目标目录
        String remoteFileName = file.getOriginalFilename(); // 远程服务器上的文件名

        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channel = null;

        try {
            session = jsch.getSession(remoteUser, remoteHost, remotePort);
            session.setPassword(remotePassword);

            // 禁用主机密钥检查（在生产环境中不推荐）
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            // 将文件上传到远程服务器
            InputStream inputStream = file.getInputStream();
            channel.put(inputStream, remoteDir + "/" + remoteFileName);
            inputStream.close();

            // 获取文件访问URL（这里需要根据实际情况生成）
            String url = "http://117.72.40.8:8080/images/test" + remoteFileName;

            System.out.println("图片上传，访问URL：" + url);
            return JsonResult.builder().data(url).message("上传成功！").code("200").build();
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
            return JsonResult.builder().data(null).message("SSH异常！").code("500").build();
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.builder().data(null).message("IO异常！").code("500").build();
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
